import {time} from '@/common/utils/time.js'
import {uploadApi} from '@/api/baseUrl.js'
import {
	storage
} from '@/common/utils/storage.js'
import store from '@/store/index'
	
export const uploadFile = function(path) {
	return new Promise((resolve, reject)=>{
		var that = this
		uni.chooseImage({
		    count: 1,
		    success(res) {
		        console.log(res);
		        if (res.tempFilePaths.length > 0) {
		            let filePath = res.tempFilePaths[0]
		            //进行上传操作
					var newTime = time.timestampToDate_ymd(Date.now())
					uniCloud.uploadFile({
						filePath:filePath,//当前图片路径
						cloudPath: path + '/' + newTime + '/' + Date.now() + '.' + 'jpg',//文件夹名
						success: (res) => {
						// console.log('上传成功', res);
						resolve(res);
						},
						fail(res) {'上传失败', res},
						complete(res) {'上传完成', res}
					})
				}
			}
		})
	})
}

export const uploadFileToService = function() {
	return new Promise((resolve, reject)=>{
		var that = this
		uni.chooseImage({
		    count: 1,
		    success(chooseImageRes) {
		        console.log(chooseImageRes);
		        if (chooseImageRes.tempFilePaths.length > 0) {
					const tempFilePaths = chooseImageRes.tempFilePaths;
					//校验上传图片的大小，不超过1M=1024KB= 1024*1024B 判断大小必须用chooseImageRes.tempFiles 不可以用chooseImageRes.tempFilePaths
					if(chooseImageRes.tempFiles[0] && chooseImageRes.tempFiles[0].size > 1024*1024*5){
						uni.showToast({
							title:'上传的头像不能超过5M哦~',
							duration:2000,
							icon:'none'
						});
						return;
					}
		            //进行上传操作
					uni.uploadFile({
						url: uploadApi,
						filePath: tempFilePaths[0],
						name: 'file',
						method: 'POST',
						timeout: 30000,
						header: {
							"clientname": store.state.clientname,
							'Authorization': 'token ' + storage.getStorageDataSync(store.state.token),
							'content-type': 'multipart/form-data' // 走网关的接口,一定要加上这个,要不支付宝小程序上传不成功
						},
						success: (uploadFileRes) => {
							console.log('uploadFileRes', uploadFileRes.data)
							var res = JSON.parse(uploadFileRes.data)
							console.log('res', res)
							if (res.code == 10000) {
								resolve(res);
							} else {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								})
							}
						}
					})
				}
			}
		})
	})
}